package com.bestcem.xm.deliver.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @ClassName: StringValue2FastJsonSerializer
 * @Description: 字符串转fastjson.JSONObject 或者字符串转fastjson.JSONArray
 * @Author: chenglong.yue
 * @Date: 2023/2/13 18:09
 */
public class StringValue2FastJsonSerializer implements ObjectSerializer {
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object != null) {
            String str = object.toString();
            if (this.isTypeJSONObject(str)) {
                serializer.write(JSONObject.parseObject(str));
            } else if (this.isTypeJSONArray(str)) {
                serializer.write(JSONArray.parseArray(str));
            } else {
                throw new IOException("格式不对");
            }
        } else {
            serializer.writeNull();
        }
    }

    private boolean isTypeJSONObject(String str) {
        boolean result = false;
        if (!ObjectUtils.isEmpty(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                result = true;
            }
        }
        return result;
    }

    private boolean isTypeJSONArray(String str) {
        boolean result = false;
        if (!ObjectUtils.isEmpty(str)) {
            str = str.trim();
            if (str.startsWith("[") && str.endsWith("]")) {
                result = true;
            }
        }
        return result;
    }
}
